import createError from "http-errors";
import Verify from "../utils/verify.js";
import transport from "../utils/email.js";
import store from "../store/index.js";
import scheduled from "../scheduled/index.js";

/**
 * @apiDefine templatePort
 * @apiSuccess {string} msg 返回信息
 * @apiError {String} msg 返回信息
 */

// 接口返回数据封装类
class TemplatePort extends Verify {
  constructor(validator, integrity = false, keys = null) {
    // 继承并调用验证类, 但没有传递验证规则
    super(validator, integrity);

    this.store = store;
    this.transport = transport;
    this.scheduled = scheduled;
    this.pkeys = keys;
  }

  P(key) {
    return async (req, res) => {
      try {
        if (this[key]) {
          let result = await this[key](req, res);
          result && res.status(200).json(result);
        } else throw createError(404, "接口不存在");
      } catch (e) {
        res.status(e.status || 400).json(this.resT(null, e.message));
      }
    };
  }

  resT(data, msg = "success") {
    data = data || {};
    let res = { msg, ...data };
    return res;
  }

  pageT(data, page, size, total, msg = "success") {
    return {
      data: data,
      page: page,
      size: size,
      total: total,
      msg: msg,
    };
  }
}

export default TemplatePort;
